<template>
	<el-dialog :visible.sync="dialogVisible" title="编辑上架信息" width="1100px" :close-on-click-modal="false" v-drag2anywhere>
		<el-form :model="formData" label-width="120px" :rules="rules" size="mini" ref="formData">

			<el-row>
				<el-col :span="12" style="">
					<el-form-item label="商品编码:">{{formData.sn==""? '无':formData.sn}}</el-form-item>
				</el-col>
        <el-col :span="12">
          <el-form-item label="商品GUID:">
            <el-input v-model="formData.guid" placeholder="军队自行采购商城商品GUID"></el-input>
          </el-form-item>
        </el-col>
			</el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="所属账套:" prop="account">
            <el-select v-model="formData.account" style="width: 100%;" @change="handleAccountChange">
              <el-option v-for="(item,index) in accounts" :label="item.name" :key="item.index" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="上架渠道:" prop="platform">
            <el-select v-model="formData.platform" @change="handlePlatformChange" style="width: 100%;">
              <el-option v-for="(item,index) in platforms" :label="item.label" :key="item.index" :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="渠道类型:" prop="platform">
            <el-select v-model="formData.platformtype" style="width: 100%;">
               <el-option label="企业" value="企业"></el-option>
              <el-option label="京东自营" value="京东自营"></el-option>
              <el-option label="京东慧采" value="京东慧采"></el-option>
              <el-option label="政采云" value="政采云"></el-option>
              <el-option label="军网" value="军网"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

      <el-col :span="18">
        <el-form-item label="申请商品名称:" prop="pretitle">
          <el-input v-model="formData.pretitle" placeholder="申请上架商品的标题"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <div style="float: right;">
          <el-form-item label="客户联系人:" prop="client">
            <el-autocomplete v-model="formData.client" placeholder="客户名" :fetch-suggestions="querySearchAsync"
              style="width: 100%;"></el-autocomplete>
          </el-form-item>
        </div>
      </el-col>
      <el-col >
        <el-form-item label="合作商名称:" prop="supname">
          <el-select v-model="formData.supname" style="width: 100%;" @change="handleSupChange">
            <el-option v-for="(item,index) in suppliers" :label="item.name" :key="item.index" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      </el-row>

				<el-row>
				  <el-col :span="12">
				    <el-row>
				      <el-col :span="12">
				        <el-form-item label="品牌:" prop="brand">
				          <el-input v-model="formData.brand" placeholder="请输入品牌"></el-input>
				        </el-form-item>
				      </el-col>
				      <el-col :span="12">
				        <el-form-item label="规格型号:" prop="brand">
				          <el-input v-model="formData.model" placeholder="规格型号"></el-input>
				        </el-form-item>
				      </el-col>
				      <el-col :span="12">
				        <el-form-item label="计量单位:" prop="unit">
				          <el-input v-model="formData.unit" placeholder="计量单位"></el-input>
				        </el-form-item>
				      </el-col>

				      <el-col :span="12">
				        <el-form-item label="最小起订量:" prop="mmq">
				          <el-input-number v-model="formData.mmq" placeholder="起订量" style="width: 100%;"></el-input-number>
				        </el-form-item>
				      </el-col>
				    </el-row>
				  </el-col>
				  <el-col :span="12">
				    <el-form-item label="详细参数:">
				      <el-input type="textarea" :rows="4" placeholder="商品详细参数" v-model="formData.params" maxlength="500"
				        show-word-limit></el-input>
				    </el-form-item>
				  </el-col>
				</el-row>
				<el-row :gutter="10">
				  <el-col :span="6">
				    <el-form-item label="需求数量:" prop="num">
				      <el-input-number v-model="formData.num" placeholder="需求数量" style="width: 100%;">
				      </el-input-number>
				    </el-form-item>
				  </el-col>
				  <el-col :span="6">
				    <el-form-item label="上架单价:" prop="price">
				      <el-input-number v-model="formData.price" :precision="4" style="width: 100%;">
				      </el-input-number>
				    </el-form-item>
				  </el-col>
          <el-col :span="6">
            <el-form-item label="JD慧采价:" prop="hcprice">
              <el-input-number v-model="formData.hcprice" :precision="4" style="width: 100%;">
              </el-input-number>
            </el-form-item>
          </el-col>

				</el-row>
				<el-row :gutter="10">
				  <el-col :span="10">
				    <el-form-item label="销售区域:" prop="allregion">
				      <el-radio-group v-model="formData.allregion">
				        <el-radio label="1">全国地区</el-radio>
				        <el-radio label="0">部分地区</el-radio>
				      </el-radio-group>
				    </el-form-item>
				  </el-col>

				  <el-col :span="14" v-if="formData.allregion=='0'">
				    <el-form-item label="指定区域:">
				      <el-input v-model="formData.region"></el-input>
				    </el-form-item>
				  </el-col>
				</el-row>
				<el-row>
				  <el-col>
				    <el-form-item label="参考链接:">
				      <el-input v-model="formData.cklink" placeholder="如果JD自营店有此产品在售,请填写在售产品链接地址!"></el-input>
				    </el-form-item>
				  </el-col>
				<el-col >
					<el-form-item label="备注信息:">
						<el-input v-model="formData.memo" type="textarea" rows="3" placeholder="备注信息"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
      <el-row>
        <el-col :span="12">
          <div class="title">产品图片</div>
          <div style="color: rgb(153, 153, 153); font-size: 12px; margin-left: 5px; margin-bottom: 20px;">
          	上传图片至少上传三张!</div>
          <div style="margin-bottom: 20px;">
          	<el-upload list-type="picture-card" ref="thumbupload" :file-list="thumbuploadConfig.imgList"
          		:action="thumbuploadConfig.action" :headers="thumbuploadConfig.headers"
          		:accept="thumbuploadConfig.accept" :limit="thumbuploadConfig.limit" :on-change="handleThumbChange"
          		:auto-upload="false" :on-remove="handleThumbRemove" :on-exceed="handleThumbLimit" multiple
          		:before-remove="handleThumbBeforRemove" :on-preview="handleThumbPreviewPreview">
          		<i class="el-icon-plus"></i>
          	</el-upload>
          	<el-dialog title="图片预览" :visible="previewImg" append-to-body style="text-align: center;"
          		@close="previewImg=false">
          		<img :src="previewUrl" />
          	</el-dialog>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="title">产品资质文件</div>
          <div style="color: rgb(153, 153, 153); font-size: 12px; margin-left: 5px; margin-bottom: 20px;">
          	请上传产品线所需资质文件，例如：商标注册证、CCC证书、厂家授权、检测报告等</div>
          <el-upload list-type="picture-card" ref="zzupload" :file-list="zzuploadConfig.imgList"
          	:action="zzuploadConfig.action" :headers="zzuploadConfig.headers" :accept="zzuploadConfig.accept"
          	:limit="zzuploadConfig.limit" :on-change="handleZZChange" :auto-upload="false"
          	:on-remove="handleZZRemove" :on-exceed="handleZZLimit" multiple :before-remove="handleZZBeforRemove"
          	:on-preview="handleZZPreviewPreview">
          	<i class="el-icon-plus"></i>
          </el-upload>
        </el-col>
      </el-row>
			<PDFViewer v-if="pdfVisible" ref="pdfUI"></PDFViewer>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="dialogVisible = false" size="medium">取 消</el-button>
			<el-button type="primary" size="medium" @click="handleSave">保存</el-button>
		</div>
	</el-dialog>
</template>

<script>
	import PDFViewer from '@/components/attachviewer.vue';
	export default {
		components: {
			PDFViewer
		},
		data() {
			var validateSize=(rule,value,callback)=>{
				if(value.x==0 || value.y==0 || value.z==0){
					callback(new Error("长宽高任意项都不能为0"));
				}else{
					callback();
				}
			};
			var validateweight=(rule,value,callback)=>{
				if(value<=0){
					callback(new Error("重量不能等于0KG!"));
				}else{
					callback();
				}
			};

			var validateprice=(rule,value,callback)=>{
				if(value<=0){
					callback(new Error("单价不能为0!"));
				}else{
					callback();
				}
			};
			return {
				index: -1,
				formData: {
					id: '',
					platformid: '-1',
					platform: '无',
					desplatform: '京东自营',
					brand: '',
					model: '',
					jdprice: 0.0,
					unit: '',
					title: '',
					params:'',
					cover:'',
					num: 1,
					allregion: 1,
					exptime: '',
					region: '',
          guid:'',
					cklink: '',
					supid: '',
					supname: '',
					status:1,
					sn: '',
					supinfo: ''
				},
        accounts:[],
				suppliers: [],
				platforms: [],
				rules: {
					platform: [{
						required: true,
						message: "上架渠道不能为空!",
						trigger: "change"
					}],
          client: [{
          	required: true,
          	message: "客户名称不能为空!",
          	trigger: "change"
          }],
					pretitle:[{
						required:true,
						message:'申请上架名称不能为空',
						trigger:'blur'
					}],
					supname: [{
						required: true,
						message: "请选择申请上架的供应商！",
						trigger: "blur"
					}],
					price: [{
						required: true,
						message: "上架价格不能为空",
						trigger: "blur"
					},{
						validator: validateprice,
						trigger: 'blur'
					}],
					num: [{
						required: true,
						message: "上架数量不能为空",
						trigger: "blur"
					}],
					unit: [{
						required: true,
						message: "计量单位不能为空",
						trigger: "blur"
					}],
					allregion: [{
						required: true,
						message: "上架数量不能为空",
						trigger: "blur"
					}],
					mmq: [{
						required: true,
						message: "最小起订量不能为空",
						trigger: "blur"
					}],
          account: [{
            required: true,
            message: "所属账套不能为空!",
            trigger: "blur"
          }]
				},
				//文件上传相关变量
				thumbuploadConfig: { //产品图片上传
					//文件上传相关参数
					accept: '.jpg,.jpeg,.png',
					limit: 6,
					headers: {
						token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
					},
					imgList: [],
					fileList: [],
					removeids: [], //要删除的id
					action: ""
				},
				//文件上传相关变量
				zzuploadConfig: { //产品图片上传
					//文件上传相关参数
					accept: '.pdf,.jpg,.jpeg,.png',
					limit: 10,
					headers: {
						token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
					},
					imgList: [],
					fileList: [],
					removeids: [], //要删除的id
					action: ""
				},
				dialogVisible: true,
				previewUrl: '',
				previewImg: false,
				pdfVisible: false,
				snexist:false
			}
		},
		mounted() {
			this.loadPlatforms();
			this.loadSuppliers();
      this.loadAccounts();
		},
		methods: {
      handleAccountChange(account){
        var option = this.accounts.filter(function(cur, index, a) {
          if (cur.name == account) {
            return cur;
          }
        })[0];
        this.formData.accountid = option.id;
        this.formData.account = option.name;
      },
      loadAccounts(){
        this.axios.post("api/admin/account/list").then((res) => {
          if (res.status == 200 && res.data.code == 0) {
            this.accounts = res.data.list;
          }
        });
      },
      querySearchAsync(str,cb){
          this.axios.post("api/admin/clientuser/filter",{username:str}).then(res=>{
            if(res.data.code){
              cb(res.data.data);
            }
          })
      },
			lockedit(){
				return this.formData.status;
			},
			initData(index, data) {
				this.index = index;
				this.formData = JSON.parse(JSON.stringify(data));
        if(this.formData.platformid==-1){
          this.formData.platform="无";
        }
				this.thumbuploadConfig.imgList = data.thumbs;
				this.zzuploadConfig.imgList = data.zizhi;
				this.formData.allregion = parseInt(this.formData.allregion);
			},
			loadPlatforms: function() {
				this.axios.get("/api/admin/platform/list").then((res) => {
					if (res.status == 200 && res.data.code == 0) {
						this.platforms = res.data.platforms;
 					}
				})
			},
			loadSuppliers: function() {
				this.axios.post("api/admin/supplier/list").then((res) => {
					if (res.status == 200 && res.data.code == 0) {
						this.suppliers = res.data.list;
					}
				});
			},
			handleSupChange: function(sup) {
				var option = this.suppliers.filter(function(cur, index, a) {
					if (cur.name == sup) {
						return cur;
					}
				})[0];
				this.formData.supid = option.id;
				this.formData.supname = option.name;
			},
			handlePlatformChange: function(platform) {
				var option = this.platforms.filter(function(cur, index, a) {
					if (cur.label == platform) {
						return cur;
					}
				})[0];
				this.formData.platformid = option.id;
				this.formData.platform = option.label;
			},
			handlechecksn:function(){
				this.axios.get("api/admin/arrival/jdarrival/checksn",{params:{sn:this.formData.sn,id:this.formData.id}}).then(res=>{
					if(res.status==200 && res.data.code==0){
						this.snexist=true;
						this.$alert("此商品编码已经存在!",{type:'error'});
					}else{
						this.snexist=false;
					}
				});
			},
			handleSave: function() {
				if(this.snexist){
					this.$alert("请仔细核对商品编码，此商品编码已经存在!",{type:'error'});
					return;
				}
				if (this.$refs.formData.validate((ok) => {
						if (ok) {

							let fd = new FormData();

							//添加要删除的附件id
							fd.append("id", this.formData.id);
							fd.append("sn",this.formData.sn);
              fd.append("guid",this.formData.guid);
							fd.append("rmthumbids", this.thumbuploadConfig.removeids.join(","));
							fd.append("rmzzids", this.zzuploadConfig.removeids.join(","));
							fd.append("platformid",this.formData.platformid=='无'? -1:this.formData.platformid),
							fd.append("platform",this.formData.platform=='无'? "":this.formData.platform),
              fd.append("platformtype",this.formData.platformtype);
							fd.append("brand", this.formData.brand);
							fd.append("model", this.formData.model);
							fd.append("pretitle",this.formData.pretitle);
							fd.append("exptime",this.formData.exptime);
 							fd.append("params",this.formData.params);
							fd.append("supid",this.formData.supid);
							fd.append("supname",this.formData.supname);
              fd.append("accountid",this.formData.accountid);
              fd.append("account",this.formData.account);
							fd.append("mmq",this.formData.mmq);
							fd.append("unit", this.formData.unit);
							fd.append("num", this.formData.num);
              fd.append("client",this.formData.client);
							fd.append("price", this.formData.price);
							fd.append("cklink", this.formData.cklink);
							fd.append("allregion", this.formData.allregion ? 1 : 0);
							fd.append("region", this.formData.region);
							fd.append("memo", this.formData.memo);
							let fid = 0;
							this.thumbuploadConfig.fileList.forEach(file => {
								if (file.raw) {
									fd.append("thumb_" + fid, file.raw);
									fid++;
								}
							});

							fid=0;
							this.zzuploadConfig.fileList.forEach(file=>{
								if(file.raw){
									fd.append("zizhi_"+fid,file.raw);
                  fid++;
								}
							});


							this.$axiosUploader.post("/api/admin/productnew/update", fd).then(res => {
								if (res.status == 200 && res.data.code == 0) {
									this.thumbuploadConfig.imgList = res.data.thumbs;
									this.zzuploadConfig.imgList=res.data.zizhi;
									this.$emit("closeHandler",this.index,this.thumbuploadConfig.imgList,this.zzuploadConfig.imgList,this.formData);
									this.dialogVisible=false;

									this.thumbuploadConfig.fileList=[];
									this.thumbuploadConfig.removeids=[];
									this.zzuploadConfig.fileList=[];
									this.zzuploadConfig.removeids=[];
									this.$refs.thumbupload.clearFiles();
									this.$refs.zzupload.clearFiles();
                  this.$message({
                  	message: "保存成功!",
                  	showClose: true,
                  	type: 'success',
                  	duration: 1500,
                  });
								}
 							});
						}
					}));
 			},
			//产品图片上传处理
			handleThumbChange: function(file, list) {
				//判断文件格式和数量
				var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
				var extarr = ['jpg', 'jpeg', 'png'];
				var sizeok = file.size / 1024 / 1024 < 2;
				if (extarr.lastIndexOf(ext) == -1) {
					this.$message.error("上传文件格式必须为" + extarr.join(","));
					//删除刚上传的文件
					this.thumbuploadConfig.fileList.splice(this.thumbuploadConfig.fileList.length - 1, 1);
					return;
				}
				if (!sizeok) {
					this.$message.error("上传文件大小最大不超过1M");
					this.thumbuploadConfig.fileList.splice(this.thumbuploadConfig.fileList.length - 1, 1);
					return;
				}

				this.thumbuploadConfig.fileList = list;
			},
			handleThumbBeforRemove: function(file, FileList) {
				return this.$confirm("此操作将会删除当前图片，是否继续?", "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
			},
			handleThumbRemove: function(file) {
				if (file.id) { //如果存储 id即为已经上传好的图片
					this.thumbuploadConfig.removeids.push(file.id);
				}
			},
			handleThumbLimit: function() {
				this.$message.warning("最多可上传" + this.thumbuploadConfig.limit + "个文件");

			},
			handleThumbPreviewPreview: function(file) {
				this.pdfVisible = true;
				this.$nextTick(() => {
					this.$refs.pdfUI.dialogVisible = true;
					this.$refs.pdfUI.initData(this.thumbuploadConfig.imgList);
				})
			},

			/***资质附件**/
			handleZZChange: function(file, list) {
				//判断文件格式和数量
				var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
				var extarr = ['jpg', 'jpeg', 'png', "doc", "docx", "xls", "xlsx", "pdf"];
				var sizeok = file.size / 1024 / 1024 < 5;
				if (extarr.lastIndexOf(ext) == -1) {
					this.$message.error("上传文件格式必须为" + extarr.join(","));
					//删除刚上传的文件
					this.zzuploadConfig.fileList.splice(this.zzuploadConfig.fileList.length - 1, 1);
					return;
				}
				if (!sizeok) {
					this.$message.error("上传文件大小最大不超过2M");
					this.zzuploadConfig.fileList.splice(this.zzuploadConfig.fileList.length - 1, 1);
					return;
				}
				this.zzuploadConfig.fileList = list;
			},
			handleZZBeforRemove: function(file, FileList) {
				return this.$confirm("此操作将会删除当前图片，是否继续?", "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
			},
			handleZZRemove: function(file) {
				if (file.id) { //如果存储 id即为已经上传好的图片
					this.zzuploadConfig.removeids.push(file.id);
				}
			},
			handleZZLimit: function() {
				this.$message.warning("最多可上传" + this.zzuploadConfig.limit + "个文件");
			},
			handleZZPreviewPreview: function(file) {
				//预览pdf文件
				this.pdfVisible = true;
				this.$nextTick(() => {
					this.$refs.pdfUI.dialogVisible = true;
					this.$refs.pdfUI.initData(this.zzuploadConfig.imgList);
				})
			}
		}
	}
</script>

<style>
	.title {
		position: relative;
		padding-left: 10px;
		margin-bottom: 15px;
		font-size: 14px;
		color: #333;
		font-weight: 700;
	}

	.title:before {
		content: "";
		position: absolute;
		top: 4px;
		left: 0;
		width: 5px;
		height: 65%;
		background-color: #249af3;
	}

	// 上传图片框样式
	.el-upload-list el-upload-list--picture-card {
		height: 96px !important;
		width: 96px !important;
		line-height: 96px !important;
	}

	.el-upload--picture-card {
		height: 96px !important;
		width: 96px !important;
		line-height: 96px !important;
	}

	.el-upload-list__item {
		height: 96px !important;
		width: 96px !important;
		line-height: 96px !important;
	}

	.el-upload-list__item-status-label i {
		position: absolute;
		width: 12x;
		right: 12px;
		top: 0px;
	}

	.el-upload--picture-card {
		height: 96px !important;
		width: 96px !important;
		line-height: 96px !important;
	}

	.el-upload-list__item {
		height: 96px !important;
		width: 96px !important;
		line-height: 96px !important;
		transition: none !important;
	}

	.el-upload-list__item-status-label i {
		position: absolute;
		width: 12x;
		right: 12px;
		top: 0px;
	}
</style>
